﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;

namespace Lilium.Web.Mvc
{
	public static class AjaxExtensions
	{
		public static void RegisterDataItem(this AjaxHelper ajaxHelper, string id, object data)
		{
			var scriptResourceData = ScriptResourceData.EnsureResourceData(ajaxHelper);
			scriptResourceData.RegisterDataItem(id, data);
		}

		public static void RegisterScript(this AjaxHelper ajaxHelper, IScriptDescriptor scriptDescriptor)
		{
			if (scriptDescriptor == null)
				throw new ArgumentNullException("scriptDescriptor");

			scriptDescriptor.RegisterScript(ajaxHelper);
		}

		public static void RenderDataItems(this AjaxHelper ajaxHelper)
		{
			var scriptResourceData = ScriptResourceData.GetResourceData(ajaxHelper);
			if (scriptResourceData != null)
				scriptResourceData.RenderDataItems(ajaxHelper);
		}

		public static void RenderResources<TScriptDescriptor>(this AjaxHelper ajaxHelper)
		{
			var scriptResourceData = ScriptResourceData.EnsureResourceData(ajaxHelper);
			foreach (var resourceReference in ScriptResourceReflectionHelper.GetResourceReferences<TScriptDescriptor>())
				scriptResourceData.RenderScriptResourceReference(ajaxHelper, resourceReference);
		}

		public static void RenderResources(this AjaxHelper ajaxHelper, IScriptDescriptor scriptDescriptor)
		{
			if (scriptDescriptor == null)
				throw new ArgumentNullException("scriptDescriptor");

			scriptDescriptor.RenderResources(ajaxHelper);
		}

		public static void RenderScripts(this AjaxHelper ajaxHelper)
		{
			var scriptResourceData = ScriptResourceData.GetResourceData(ajaxHelper);
			if (scriptResourceData != null)
				scriptResourceData.RenderClientScripts(ajaxHelper);
		}
	}
}